//
//  ConsulationSearchV2ViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/22.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "ConsulationSearchV2ViewController.h"

#import "ConsulationV2AnswerInfoViewController.h"

#import "ConsulationAnsedListCell.h"

@interface ConsulationSearchV2ViewController () <UISearchBarDelegate>

/// 模型视图
@property (nonatomic, readonly, strong) ConsulationSearchV2ViewModel* viewModel;

// UI

//IBOutlet
@property (nonatomic, weak) IBOutlet UITableView* currentTableView;
@property (nonatomic, weak) IBOutlet UISearchBar* searchBar;

@property (nonatomic, strong) UIButton* btnAccessoryView;

@end

@implementation ConsulationSearchV2ViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initLoadForRAC];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // hide sys navBar
    self.fd_prefersNavigationBarHidden = NO;
    // 去掉侧滑pop手势
    self.fd_interactivePopDisabled = YES;
    // create subViews
    [self _setupSubViews];
    // deal action
    [self _dealAction];
    /// tableView rigister  cell
    [self.tableView mh_registerNibCell:[ConsulationAnsedListCell class]];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData
{
    
}

- (void)initLoadForRAC
{
    @weakify(self)
    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
}

- (void)initUI
{
    @weakify(self);
    
    // 遮盖层
    _btnAccessoryView = [[UIButton alloc] initWithFrame:CGRectMake(0, MH_APPLICATION_STATUS_BAR_HEIGHT + 58.0f, self.view.bounds.size.width, self.view.bounds.size.height)];
    [_btnAccessoryView setBackgroundColor:[UIColor blackColor]];
    [_btnAccessoryView setAlpha:0.0f];
    [_btnAccessoryView addTarget:self action:@selector(_clickControlAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnAccessoryView];
}

#pragma mark - Override
- (void)bindViewModel
{
    [super bindViewModel];
    
    @weakify(self)
    
    RACSignal* willAppearSignal = [[self rac_signalForSelector:@selector(viewWillAppear:)] replay];
    RACSignal* didAppearSignal = [[self rac_signalForSelector:@selector(viewDidAppear:)] replay];
    RACSignal* viewDidLayoutSVSignal = [[self rac_signalForSelector:@selector(viewDidLayoutSubviews)] replay];
    
    [willAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
    }];
    
    [didAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        // ScrollView 内容 未能在此时才约束
        
        //Request
    }];
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
    
    [[[viewDidLayoutSVSignal take:1] deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self)
         
         //重置 更新 frame
         [self _setupAllView];
     }];
    
#pragma mark -- bindViewModel
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    self.viewModel.didSelectCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSIndexPath *indexPath) {
        @strongify(self);
        
        [self _push2AskDetailVC:indexPath];
        
        return [RACSignal empty];
    }];
    
    [[self.viewModel.requestRemoteDataCommand.errors deliverOnMainThread] subscribeNext:^(NSError* error)
     {
         @strongify(self);
         
         /// 处理验证错误的error
         if ([error.domain isEqualToString:SUCommandErrorDomain]) {
             [MBProgressHUD mh_showTips:error.userInfo[SUCommandErrorUserInfoKey]];
             return ;
         }
         [MBProgressHUD mh_showErrorTips:error];
     }];
}

- (UITableView*)customTableView
{
    return self.currentTableView;
}

#pragma mark - 更新初始化 操作
- (void)_setupSubViews
{
    // 搜索栏
    UITextField *textfield = [self.searchBar valueForKey:@"_searchField"];
    //    [textfieldsetValue:color(0x999999, 1.0f)forKeyPath:@"_placeholderLabel.textColor"];
    [textfield setValue:[UIFont systemFontOfSize:14.0f]forKeyPath:@"_placeholderLabel.font"];
    
    self.searchBar.delegate = self;
}

- (void)_setupAllView
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
}

#pragma mark - 事件处理
/// 事件处理
- (void)_dealAction
{
    @weakify(self);
    
}

// 遮罩层（按钮）-点击处理事件
- (void)_clickControlAction:(id)sender
{
    NSLog(@"handleTaps");
    [self _controlAccessoryView:0];
}

// 控制遮罩层的透明度
- (void)_controlAccessoryView:(float)alphaValue
{
    [UIView animateWithDuration:0.2 animations:^
     {
         //动画代码
         [self.btnAccessoryView setAlpha:alphaValue];
     }completion:^(BOOL finished)
     {
         if (alphaValue<=0)
         {
             [self.searchBar resignFirstResponder];
             [self.searchBar setShowsCancelButton:NO animated:YES];
             [self.navigationController setNavigationBarHidden:NO animated:YES];
         }
     }];
}

#pragma mark - Delegate 一些无法用RAC实现
#pragma mark - UISearchBarDelegate 协议
// UISearchBar得到焦点并开始编辑时，执行该方法
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [self.searchBar setShowsCancelButton:YES animated:YES];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    [self _controlAccessoryView:0.9];// 显示遮盖层。
    
    return YES;
}

// 取消按钮被按下时，执行的方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar resignFirstResponder];
    
    [self.searchBar setShowsCancelButton:NO animated:YES];
    
    //    [liveViewAreaTable searchDataBySearchString:nil];// 搜索tableView数据
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    [self _controlAccessoryView:0];// 隐藏遮盖层。
}

// 键盘中，搜索按钮被按下，执行的方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"---%@",searchBar.text);
    
    [self.searchBar resignFirstResponder];// 放弃第一响应者
    
    self.viewModel.search = searchBar.text;
//    [self.viewModel searchCityByName:searchBar.text];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    [self _controlAccessoryView:0];// 隐藏遮盖层。
}

// 当搜索内容变化时，执行该方法。很有用，可以实现时实搜索
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"textDidChange---%@",searchBar.text);
    
    //    [liveViewAreaTable searchDataBySearchString:searchBar.text];// 搜索tableView数据
    
    //    [self _controlAccessoryView:0];// 隐藏遮盖层。
}

// UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}

//// 下拉刷新
- (void)tableViewDidTriggerHeaderRefresh{
    /// 先调用父类的加载数据
    [super tableViewDidTriggerHeaderRefresh];
}
/// config  cell
- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
{
    return [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ConsulationAnsedListCell class])];
}

/// config  data
- (void)configureCell:(ConsulationAnsedListCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(ConsulationAnsedListCellModel *)object
{
    /// config data (PS：由于MVVM主要是View与数据之间的绑定，但是跟 setViewModel: 差不多啦)
    [cell bindViewModel:object];
}

/// 文本内容区域
//- (UIEdgeInsets)contentInset
//{
//    return UIEdgeInsetsZero;
//}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    /// 由于使用系统的autoLayout来计算cell的高度，每次滚动时都要重新计算cell的布局以此来获得cell的高度 这样一来性能不好
    /// 所以笔者采用实现计算好的cell的高度
    
    return [self.viewModel.dataSource[indexPath.row] cellHeight];
}

////////////////// 以下为UI代码，不必过多关注 ///////////////////
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    /// FIXED : when data is empty ，the backgroundColor is exist
    return .0001f;
}


#pragma mark-代理方法
// 设立实现代理，注意要返回UIModalPresentationNone
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}

#pragma mark - 功能

#pragma mark - 跳转
- (void)_push2AskDetailVC:(NSIndexPath*)indexPath
{
    ConsulationAnsedListCellModel* cellModel = self.viewModel.dataSource[indexPath.row];
    ConsulationListData* data = cellModel.data;
    
    ConsulationV2AnswerInfoViewModel* vm = [[ConsulationV2AnswerInfoViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"最新回复详情"}];
    ConsulationV2AnswerInfoViewController* vc = [[ConsulationV2AnswerInfoViewController alloc] initWithViewModel:vm];
    [self.navigationController pushViewController:vc animated:YES];
}

@end
